//
//  XMNetworkManager.m
//  DATABK
//
//  Created by 俞渊华 on 2017/4/21.
//  Copyright © 2017年 俞渊华. All rights reserved.
//

#import "XMNetworkManager.h"
#import "AFNetworking.h"
#import "XMNetworkCache.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "MHUploadParam.h"
#import "MBProgressHUD.h"

#ifdef DEBUG
#define XMLog(...) printf("[%s] %s [第%d行]: %s\n", __TIME__ ,__PRETTY_FUNCTION__ ,__LINE__, [[NSString stringWithFormat:__VA_ARGS__] UTF8String])
#else
#define XMLog(...)
#endif

#define MHAsi_API_TIME_OUT 20


static BOOL _isOpenLog;   // 是否已开启日志打印
static NSMutableArray *_allSessionTask;
static NSMutableArray *_allSessionTask;
static AFHTTPSessionManager *_sessionManager;

@implementation XMNetworkManager

#pragma mark - 开始监听网络
+ (void)networkStatusWithBlock:(XMNetworkStatus)networkStatus {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            switch (status) {
                case AFNetworkReachabilityStatusUnknown:
                    networkStatus ? networkStatus(XMNetworkStatus_Unknown) : nil;
                    if (_isOpenLog) XMLog(@"未知网络");
                    break;
                case AFNetworkReachabilityStatusNotReachable:
                    networkStatus ? networkStatus(XMNetworkStatus_NotReachable) : nil;
                    if (_isOpenLog) XMLog(@"无网络");
                    break;
                case AFNetworkReachabilityStatusReachableViaWWAN:
                    networkStatus ? networkStatus(XMNetworkStatus_ReachableViaWWAN) : nil;
                    if (_isOpenLog) XMLog(@"手机自带网络");
                    break;
                case AFNetworkReachabilityStatusReachableViaWiFi:
                    networkStatus ? networkStatus(XMNetworkStatus_ReachableViaWiFi) : nil;
                    if (_isOpenLog) XMLog(@"WIFI");
                    break;
            }
        }];
    });
}

+ (BOOL)isNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachable;
}

+ (BOOL)isWWANNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachableViaWWAN;
}

+ (BOOL)isWiFiNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachableViaWiFi;
}

+ (void)openLog {
    _isOpenLog = YES;
}

+ (void)closeLog {
    _isOpenLog = NO;
}

+ (void)cancelAllRequest {
    // 锁操作
    @synchronized(self) {
        [[self allSessionTask] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            [task cancel];
        }];
        [[self allSessionTask] removeAllObjects];
    }
}

+ (void)cancelRequestWithURL:(NSString *)URL {
    if (!URL) { return; }
    @synchronized (self) {
        [[self allSessionTask] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([task.currentRequest.URL.absoluteString hasPrefix:URL]) {
                [task cancel];
                [[self allSessionTask] removeObject:task];
                *stop = YES;
            }
        }];
    }
}

+ (NSURLSessionTask *)GET:(NSString *)URL
               parameters:(id)parameters
                  success:(XMHttpRequestSuccess)success
                  failure:(XMHttpRequestFailed)failure {
    return [self GET:URL parameters:parameters responseCache:nil success:success failure:failure];
}
#pragma mark - GET请求自动缓存
+ (NSURLSessionTask *)GET:(NSString *)URL
               parameters:(id)parameters
            responseCache:(XMHttpRequestCache)responseCache
                  success:(XMHttpRequestSuccess)success
                  failure:(XMHttpRequestFailed)failure {
    //读取缓存
    responseCache!=nil ? responseCache([XMNetworkCache httpCacheForURL:URL parameters:parameters]) : nil;
    
    NSURLSessionTask *sessionTask = [_sessionManager GET:URL parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (_isOpenLog) {XMLog(@"responseObject = %@",responseObject);}
        [[self allSessionTask] removeObject:task];
        success ? success(responseObject) : nil;
        //对数据进行异步缓存
        responseCache!=nil ? [XMNetworkCache setHttpCache:responseObject URL:URL parameters:parameters] : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (_isOpenLog) {XMLog(@"error = %@",error);}
        [[self allSessionTask] removeObject:task];
        failure ? failure(error) : nil;
        
    }];
    // 添加sessionTask到数组
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
    
    return sessionTask;
}


#pragma mark - POST请求无缓存
+ (NSURLSessionTask *)POST:(NSString *)URL
                parameters:(id)parameters
                   success:(XMHttpRequestSuccess)success
                   failure:(XMHttpRequestFailed)failure {
    return [self POST:URL parameters:parameters responseCache:nil success:success failure:failure];
}

#pragma mark - POST请求自动缓存
+ (NSURLSessionTask *)POST:(NSString *)URL
                parameters:(id)parameters
             responseCache:(XMHttpRequestCache)responseCache
                   success:(XMHttpRequestSuccess)success
                   failure:(XMHttpRequestFailed)failure {
    //读取缓存
    responseCache!=nil ? responseCache([XMNetworkCache httpCacheForURL:URL parameters:nil]) : nil;
    
    NSURLSessionTask *sessionTask = [_sessionManager POST:URL parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (_isOpenLog) {XMLog(@"responseObject = %@",responseObject);}
        [[self allSessionTask] removeObject:task];
        success ? success(responseObject) : nil;
        //对数据进行异步缓存
        responseCache!=nil ? [XMNetworkCache setHttpCache:responseObject URL:URL parameters:nil] : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (_isOpenLog) {XMLog(@"error = %@",error);}
        [[self allSessionTask] removeObject:task];
        failure ? failure(error) : nil;
        
    }];
    
    // 添加最新的sessionTask到数组
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
    return sessionTask;
}

/**
 *  上传文件
 *
 *  @param url          上传文件的 url 地址
 *  @param paramsDict   参数字典
 *  @param successBlock 成功
 *  @param failureBlock 失败
 *  @param showHUD      显示 HUD
 */
+ (void)uploadFileWithURL:(NSString*)url
                   params:(NSDictionary*)paramsDict
             successBlock:(XMHttpRequestSuccess)successBlock
             failureBlock:(XMHttpRequestFailed)failureBlock
              uploadParam:(MHUploadParam *)uploadParam
                  showHUD:(BOOL)showHUD{
    if (uploadParam) {
        [XMNetworkManager uploadFileWithURL:url params:paramsDict successBlock:successBlock failureBlock:failureBlock uploadParams:@[uploadParam] showHUD:showHUD];
    }else{
        [XMNetworkManager uploadFileWithURL:url params:paramsDict successBlock:successBlock failureBlock:failureBlock uploadParams:nil showHUD:showHUD];
    }

    
}

+ (void)uploadFileWithURL:(NSString*)url
                   params:(NSDictionary*)paramsDict
             successBlock:(XMHttpRequestSuccess)successBlock
             failureBlock:(XMHttpRequestFailed)failureBlock
             uploadParams:(NSArray *)uploadParams
                  showHUD:(BOOL)showHUD{
    
    if (showHUD) {
        [MBProgressHUD showHUDAddedTo:nil animated:YES];
    }
    
    NSLog(@"上传图片接口 URL-> %@",url);
    NSLog(@"上传图片的参数-> %@",paramsDict);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 120;
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager POST:url parameters:paramsDict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        for (MHUploadParam * uploadParam  in uploadParams) {
            [formData appendPartWithFileData:uploadParam.data name:uploadParam.name fileName:uploadParam.fileName mimeType:uploadParam.mimeType];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"uploadProgress == %@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"----> %@",responseObject);
        
        [MBProgressHUD hideHUDForView:nil animated:YES];
        if (successBlock)  successBlock(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"----> %@",error.domain);
        
        [MBProgressHUD hideAllHUDsForView:nil animated:YES];
        if (error) failureBlock(error);
    }];
    
}





#pragma mark - 初始化AFHTTPSessionManage
/**
 开始监测网络状态
 */
+ (void)load {
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

+ (void)initialize {
    _sessionManager = [AFHTTPSessionManager manager];
    
    //👇下面两行的顺序不能调换，否则超时时间无效
    _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    // 设置请求的超时时间
    _sessionManager.requestSerializer.timeoutInterval = MHAsi_API_TIME_OUT;
    
//    _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/html", nil];
    _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    _sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
}


/**
 存储着所有的请求task数组
 */
+ (NSMutableArray *)allSessionTask {
    if (!_allSessionTask) {
        _allSessionTask = [[NSMutableArray alloc] init];
    }
    return _allSessionTask;
}

@end
